<template>
  <div class="goods_cate">
    <div class="nav">
      <div class="navCon  acea-row row-between-wrapper">
        <div class="list acea-row row-middle">
          <div class="item" :class="current === index ? 'font-color' : ''" v-for="(item, index) in categoryList"
            :key="index" @click="category(index)">
            {{ item.cate_name }}
          </div>
        </div>
      </div>
    </div>
    <div class="wrapper ">
      <div class="acea-row">
        <div class="name">分類：</div>
        <div class="list acea-row row-middle">
          <div class="item" :class="erCurrent === index ? 'font-color' : ''" v-for="(item, index) in categoryCurrent"
            :key="index" @click="erCategory(item.id, index)">
            {{ item.cate_name }}
          </div>
        </div>
      </div>
      <div class="sort acea-row">
        <div class="name">排序：</div>
        <div class="acea-row row-middle">
          <div class="item" :class="iSdefaults === 0 ? 'font-color' : ''" @click="defaults">
            默認
          </div>
          <div class="item" :class="iSdefaults === 1 ? 'font-color' : ''" @click="priceSort('desc')"
            v-if="priceOrder === 'asc'">
            價格
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-jiageshaixuanshang"></use>
            </svg>
          </div>
          <div class="item" :class="iSdefaults === 1 ? 'font-color' : ''" @click="priceSort('asc')"
            v-else-if="priceOrder === ''">
            價格
            <span class="iconfont icon-jiageshaixuan"></span>
          </div>
          <div class="item" :class="iSdefaults === 1 ? 'font-color' : ''" @click="priceSort('')" v-else>
            價格
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-jiageshaixuanxia"></use>
            </svg>
          </div>
          <div class="item" :class="iSdefaults === 2 ? 'font-color' : ''" @click="timeNews">
            上架時間
            <span class="iconfont icon-shangjiashijian" :class="news ? 'font-color' : ''"></span>
          </div>
        </div>
      </div>
    </div>
    <div class="goods-container">
      <div class="goods" v-if="productslist.length">
        <ProductCard v-for="(item, index) in productslist" :key="index" :product="item" @click="goDetail(item)"
          class="goods-cate-card" />
      </div>
      <div class="loadingicon acea-row row-center-wrapper" v-if="productslist.length && productslist.length >= limit">
        <span class="loading iconfont icon-jiazai" v-if="!pullRefreshss"></span>{{ title }}
      </div>
    </div>
    <div class="noGoods" v-if="!productslist.length">
      <div class="pictrue">
        <img src="../assets/images/noGoods.png" />
      </div>
      <div class="name">親，该分類暂無商品哟~</div>
    </div>
  </div>
</template>

<script>
import ProductCard from '~/components/ProductCard.vue'

export default {
  name: "goods_cate",
  auth: false,
  components: {
    ProductCard
  },
  data() {
    return {
      categoryList: [],
      categoryCurrent: [],
      current: 0,
      moreCurrent: 0,
      seen: false,
      titleName: "",
      erCurrent: 0,
      iSdefaults: 0,
      productslist: [],
      pullRefreshss: true, // 代表可以进行下拉加載，false代表不能
      page: 1, //代表页面的初始页数
      limit: 10,
      scollY: null, // 离底部距离有多少
      pageTotal: 0, //總页数
      title: "下拉加載更多",
      cid: 0, //一级分類
      sid: 0, //二级分類
      priceOrder: "",
      news: 0,
    };
  },
  async asyncData({ app, query }) {
    let [categoryMsg] = await Promise.all([
      //获取banner分類
      app.$axios.get("/category"),
    ]);
    let category = categoryMsg.data;
    category.forEach((item) => {
      item.children.unshift({
        id: 0,
        cate_name: "全部",
      });
    });
    let cidIndex = query.cidIndex ? query.cidIndex : 0,
      cid = query.cid
        ? query.cid
        : categoryMsg.data.length
          ? categoryMsg.data[0].id
          : 0,
      sid = query.sid ? query.sid : 0,
      sidIndex = query.sidIndex ? parseInt(query.sidIndex) + 1 : 0,
      sidCategory =
        query.cid && categoryMsg.data.length
          ? categoryMsg.data[parseInt(cidIndex)].children
          : categoryMsg.data.length
            ? categoryMsg.data[0].children
            : "",
      titleName =
        query.cid && categoryMsg.data.length
          ? categoryMsg.data[parseInt(cidIndex)].cate_name
          : categoryMsg.data.length
            ? categoryMsg.data[0].cate_name
            : "";
    return {
      categoryList: category,
      categoryCurrent: sidCategory,
      titleName: titleName,
      cid: parseInt(cid),
      sid: parseInt(sid),
      current: parseInt(cidIndex),
      erCurrent: sidIndex,
      moreCurrent: parseInt(cidIndex),
    };
  },
  fetch({ store }) {
    store.commit("isHeader", true);
    store.commit("isFooter", true);
  },
  head() {
    return {
      title: "商品分類-" + this.$store.state.titleCon,
    };
  },
  created() {
    this.getProductslist();
  },
  mounted() {
    this.pullRefresh();
    // 确保页面滚动到顶部
    this.$nextTick(() => {
      window.scrollTo(0, 0);
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
    });
    // 確保頭部組件顯示
    this.$store.commit("isHeader", true);
  },
  beforeDestroy() {
    window.onscroll = null;
  },
  methods: {
    goDetail(item) {
      let path = item.presale
        ? (path = {
          path: "/goods_presell_detail",
          query: {
            id: item.id,
          },
        })
        : (path = { path: `/goods_detail/${item.id}` });
      this.$router.push(path);
    },
    getProductslist() {
      let _this = this,
        currentPage = {
          page: this.page,
          limit: this.limit,
          cid: this.cid,
          sid: this.sid,
          priceOrder: this.priceOrder,
          news: this.news,
        };
      _this.$axios
        .get("/pc/get_products", {
          params: currentPage,
        })
        .then(function (res) {
          _this.pageTotal = res.data.count;
          // 请求完成后，把得到的數據拼接到当前dom里面
          _this.productslist = _this.productslist.concat(res.data.list);
        })
        .catch(function (err) {
          _this.$message.error(err);
        });
    },
    // 下拉加載ajax
    pullRefresh: function () {
      var _this = this;
      window.onscroll = function () {
        _this.scrollChange();
      };
    },
    scrollChange: function () {
      let _this = this;
      this.scollY =
        this.comsys.getScrollTop() +
        this.comsys.getWindowHeight() -
        this.comsys.getScrollHeight();
      // 把下拉刷新置為false，防止多次请求
      if (this.scollY >= -50) {
        if (this.page > Math.ceil(this.pageTotal / this.limit)) {
          this.title = "已没有更多數據";
          this.pullRefreshss = true;
          return false;
        }
        if (!this.pullRefreshss) {
          return false;
        }
        _this.pullRefreshss = false;
        _this.title = "正在加載中....";
        // 加页碼数
        this.page++;
        _this.getProductslist();
      } else {
        // 其他时候把下拉刷新置為true
        _this.pullRefreshss = true;
        this.title = "下拉加載更多";
      }
    },
    category(index) {
      this.current = index;
      this.moreCurrent = index;
      this.categoryCurrent = this.categoryList[index].children;
      this.titleName = this.categoryList[index].cate_name;
      this.productslist = [];
      this.pullRefreshss = true;
      this.page = 1;
      this.cid = this.categoryList[index].id;
      this.sid = 0;
      this.erCurrent = 0;
      this.priceOrder = "";
      this.news = 0;
      this.getProductslist();
    },
    enter() {
      this.current = -1;
      this.seen = true;
    },
    leave() {
      this.seen = false;
      this.current = this.moreCurrent;
    },
    moreItem(index) {
      this.moreCurrent = index;
      this.categoryCurrent = this.categoryList[index].children;
      this.titleName = this.categoryList[index].cate_name;
      this.seen = false;
      this.current = index;
      this.productslist = [];
      this.pullRefreshss = true;
      this.page = 1;
      this.cid = this.categoryList[index].id;
      this.sid = 0;
      this.erCurrent = 0;
      this.priceOrder = "";
      this.news = 0;
      this.getProductslist();
    },
    erCategory(id, index) {
      this.erCurrent = index;
      this.productslist = [];
      this.pullRefreshss = true;
      this.page = 1;
      this.sid = id;
      this.priceOrder = "";
      this.news = 0;
      this.getProductslist();
    },
    defaults() {
      this.iSdefaults = 0;
      this.productslist = [];
      this.pullRefreshss = true;
      this.page = 1;
      this.news = 0;
      this.priceOrder = "";
      this.getProductslist();
    },
    priceSort(sort) {
      this.iSdefaults = 1;
      this.productslist = [];
      this.pullRefreshss = true;
      this.page = 1;
      this.news = 0;
      this.priceOrder = sort;
      this.getProductslist();
    },
    timeNews() {
      this.iSdefaults = 2;
      this.productslist = [];
      this.pullRefreshss = true;
      this.priceOrder = "";
      this.page = 1;
      this.news = !this.news === true ? 1 : 0;
      this.getProductslist();
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/assets/css/variables.scss";

.goods_cate {
  padding: 0 min(160px, 8vw);
  padding-top: 100px;

  .noGoods {
    text-align: center;

    .pictrue {
      width: 274px;
      height: 174px;
      margin: 130px auto 0 auto;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .name {
      font-size: 14px;
      color: #969696;
      margin-top: 20px;
      margin-bottom: 290px;
    }
  }

  .nav {
    width: 100%;
    background: #fff;
    border-radius: 2px;
    margin: 20px 0;
    cursor: pointer;

    .navCon {
      padding: 0 16px;
      width: 100%;

      .list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        width: 100%;

        .item {
          padding: 8px 16px;
          border-radius: 4px;
          font-size: 14px;
          font-weight: 500;
          color: #666;
          background: #f8f9fa;
          border: 1px solid transparent;
          transition: all 0.3s ease;
          white-space: nowrap;
          letter-spacing: 1px;

          &:hover {
            color: $primary-color;
            background: #fff2f0;
            border-color: #fff2f0;
          }

          &.font-color {
            color: #fff;
            background: $primary-color;
            border-color: $primary-color;
            box-shadow: 0 2px 8px rgba(233, 51, 35, 0.3);
          }
        }
      }
    }
  }

  .wrapper {
    background: #fff;
    border-radius: 2px;
    padding: 20px 16px;
    margin: 20px 0;
    border-top: 1px solid #f0f0f0;
    cursor: pointer;

    .acea-row {
      display: flex;
      align-items: center;
      flex-wrap: nowrap;
      gap: 16px;

      &:not(:last-child) {
        margin-bottom: 16px;
        padding-bottom: 16px;
      }
    }

    .list {
      display: flex;
      flex-wrap: wrap;
      gap: 24px;
      width: 100%;

      .item {
        padding: 6px 12px;
        border-radius: 4px;
        font-size: 13px;
        color: #666;
        background: #f8f9fa;
        border: 1px solid transparent;
        transition: all 0.3s ease;
        white-space: nowrap;
        letter-spacing: 1px;

        &:hover {
          color: $primary-color;
          background: #fff2f0;
          border-color: #fff2f0;
        }

        &.font-color {
          color: $primary-color;
          background: #fff2f0;
          border-color: $primary-color;
          font-weight: 500;
        }
      }
    }

    .name {
      color: #333;
      font-weight: 500;
      font-size: 14px;
      min-width: 48px;
      flex-shrink: 0;
    }

    .sort {
      .acea-row {
        margin-bottom: 0;
        padding-bottom: 0;
        border-bottom: none;
      }

      .item {
        display: flex;
        align-items: center;
        padding: 6px 12px;
        border-radius: 4px;
        font-size: 13px;
        color: #666;
        background: #f8f9fa;
        border: 1px solid transparent;
        transition: all 0.3s ease;
        white-space: nowrap;
        margin-right: 8px;
        letter-spacing: 1px;

        &:hover {
          color: $primary-color;
          background: #fff2f0;
          border-color: #fff2f0;
        }

        &.font-color {
          color: $primary-color;
          background: #fff2f0;
          border-color: $primary-color;
          font-weight: 500;
        }

        .icon {
          font-size: 12px;
          margin-left: 4px;
        }

        .iconfont {
          font-size: 12px;
          margin-left: 4px;

          &.font-color {
            color: $primary-color;
          }
        }
      }
    }
  }

  .goods-container {
    margin-bottom: 40px;
  }

  .goods {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 3rem 1.5rem;
    align-items: start;
    width: 100%;
    margin: 0 auto;

    @media (max-width: 1200px) {
      grid-template-columns: repeat(3, 1fr);
    }

    @media (max-width: 900px) {
      grid-template-columns: repeat(2, 1fr);
      gap: 1.5rem 1rem;
    }

    @media (max-width: 600px) {
      grid-template-columns: 1fr;
      gap: 1.5rem;
    }

  }
}
</style>
